/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package thesis.haipv.qa.persistence;

import com.mysql.jdbc.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import thesis.haipv.qa.model.Answer;
import thesis.haipv.qa.model.Question;
import thesis.haipv.qa.model.UserProfile;


/**
 *
 * @author PHANHAI
 */
public class AnswerDAO {
    
    private DatabaseContext db;
    
    public AnswerDAO() {
        db = DatabaseContext.getInstance();
    }
    
    public void createAnswer(String id, String content, String questionId, String responderId, long createtime) {
        String query = "INSERT INTO answers (Id, Content, QuestionId, ResponderId, CreateTime) "
                + "VALUES(?, ?, ?, ?, ?)";
        try {
            PreparedStatement ps = (PreparedStatement) db.getConnection().prepareStatement(query);
            ps.setString(1, id);
            ps.setString(2, content);
            ps.setString(3, questionId);
            ps.setString(4, responderId);
            ps.setLong(5, createtime);
            ps.executeUpdate();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
    
    public void updateRate(String id, int rate) {
        String query = "UPDATE answers SET Rate = ? WHERE Id = ?";
        try {
            PreparedStatement ps = (PreparedStatement) db.getConnection().prepareStatement(query);
            ps.setInt(1, rate);
            ps.setString(2, id);
            ps.executeUpdate();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
    
    public ArrayList<Answer> getAnswers(String qid) {
        ArrayList<Answer> answers = new ArrayList<>();
        UserProfileDAO udao = new UserProfileDAO();
        String query = "SELECT a.Id, a.Content, a.CreateTime, a.Rate, u.Fullname, u.AccountId, "
                + "SUM(CASE WHEN f.Trust = 1 THEN 1 ELSE 0 END) AS c_trust, "
                + "SUM(CASE WHEN f.Trust = 0 THEN 1 ELSE 0 END) AS c_untrust "
                + "FROM answers a "
                + "JOIN userprofiles u ON a.ResponderId = u.AccountId "    
                + "LEFT JOIN feedbacks f ON f.AnswerId = a.Id "
                + "WHERE a.QuestionId = ? "
                + "GROUP BY f.AnswerId, a.ResponderId "
                + "ORDER BY c_trust DESC";

        try {
            PreparedStatement ps = (PreparedStatement) db.getConnection().prepareStatement(query);
            ps.setString(1, qid);
            ResultSet rs = ps.executeQuery();
            while(rs.next()) {
                Answer a = new Answer();
                a.setId(rs.getString("a.Id"));
                a.setContent(rs.getString("a.Content"));
                a.setCreateTime(rs.getLong("a.CreateTime"));
                a.setNumTrust(rs.getInt("c_trust"));
                a.setNumUntrust(rs.getInt("c_untrust"));
                a.setRate(rs.getInt("a.Rate"));
                UserProfile responder = new UserProfile(rs.getString("u.AccountId"), rs.getString("u.Fullname"));
                responder.setReferenceTrust(udao.getReferienceTrust(responder.getAccountId()));
                a.setResponder(responder);
                answers.add(a);
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        return answers;
    }
    
    public ArrayList<Answer> getAnswersByUser(String userId) {
        ArrayList<Answer> answers = new ArrayList<>();
        UserProfileDAO udao = new UserProfileDAO();
        String query = "SELECT a.Id, a.Content, a.CreateTime, a.Rate, u.Fullname, u.AccountId, q.Subject, q.Id "
                + "FROM answers a "
                + "JOIN userprofiles u ON a.ResponderId = u.AccountId "    
                + "LEFT JOIN feedbacks f ON f.AnswerId = a.Id "
                + "LEFT JOIN questions q ON q.Id = a.QuestionId "
                + "WHERE a.ResponderId = ? ";
        
        try {
            PreparedStatement ps = (PreparedStatement) db.getConnection().prepareStatement(query);
            ps.setString(1, userId);
            ResultSet rs = ps.executeQuery();
            while(rs.next()) {
                Answer a = new Answer();
                a.setId(rs.getString("a.Id"));
                a.setContent(rs.getString("a.Content"));
                a.setCreateTime(rs.getLong("a.CreateTime"));
                a.setRate(rs.getInt("a.Rate"));
                UserProfile asker = new UserProfile(rs.getString("u.AccountId"), rs.getString("u.Fullname"));
                Question question = new Question();
                question.setSubject(rs.getString("q.Subject"));
                question.setId(rs.getString("q.Id"));
                question.setAsker(asker);
                a.setQuestion(question);
                answers.add(a);
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        return answers;
    }
    
}
